package com.jtny.nytb.config.datafactor.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jtny.component.core.domain.BaseDO;
import com.jtny.component.core.util.PageUtils;
import com.jtny.component.entity.PageData;
import com.jtny.component.enums.GenericStatusEnum;
import com.jtny.component.exception.ServiceException;
import com.jtny.component.util.Assert;
import com.jtny.component.util.BeanUtils;
import com.jtny.nytb.config.dataalarm.dao.DataAlarmDAO;
import com.jtny.nytb.config.dataalarm.domain.DataAlarmDO;
import com.jtny.nytb.config.dataalgorithm.service.impl.DataAlgorithmServiceImpl;
import com.jtny.nytb.dataparam.property.CodeRuleProperty;
import com.jtny.nytb.dataparam.service.serviceImpl.ConfigRuleManagementServiceImpl;
import com.jtny.nytb.equipment.dao.dataalgorithm.DataAlgorithmDAO;
import com.jtny.nytb.equipment.dao.dataalgorithm.DataAlgorithmFormulaConfigDAO;
import com.jtny.nytb.equipment.dao.dataalgorithm.DataAlgorithmParamConfigDAO;
import com.jtny.nytb.equipment.dao.dataalgorithm.DataAlgorithmScriptConfigDAO;
import com.jtny.nytb.equipment.domain.dataalgorithm.DataAlgorithmDO;
import com.jtny.nytb.equipment.domain.dataalgorithm.DataAlgorithmFormulaConfigDO;
import com.jtny.nytb.equipment.domain.dataalgorithm.DataAlgorithmParamConfigDO;
import com.jtny.nytb.equipment.domain.dataalgorithm.DataAlgorithmScriptConfigDO;
import com.jtny.nytb.config.datafactor.DataParamExcel.*;
import com.jtny.nytb.dataparam.bo.ItemBO;
import com.jtny.nytb.config.datafactor.dto.*;
import com.jtny.nytb.config.datafactor.enums.DataParamSourceEnum;
import com.jtny.nytb.config.datafactor.service.ConfigDataParamManagementService;
import com.jtny.nytb.equipment.dao.datalabel.DataLabelItemDAO;
import com.jtny.nytb.equipment.domain.datalabel.DataLabelDO;
import com.jtny.nytb.equipment.domain.datalabel.DataLabelItemDO;
import com.jtny.nytb.dataparam.dao.*;
import com.jtny.nytb.dataparam.domain.*;
import com.jtny.nytb.dataparam.vo.DevicePageQueryVO;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 规则管理配置DAO接口
 *
 * @author 智慧能源中心 - 刘琦
 * @package com.jtny.nytb.config.datafactor.service.impl
 * @fileName ConfigDataParamManagementServiceImpl .java
 * @createTime 2023/9/6 9:08
 * @Copyright© 2023 jtny
 * 江投能源技术研究院 版权所有
 */
@Service
@AllArgsConstructor
public class ConfigDataParamManagementServiceImpl
        extends ServiceImpl<ConfigDataParamManagementDAO, ConfigDataParamManagementDO>
        implements ConfigDataParamManagementService {
    private final String ALGORITHM_TYPE_FORMULA = "参量";
    private ConfigDataParamManagementDAO dataParamManagementDAO;
    private ConfigDataParamAlgorithmRelationDAO algorithmRelationDAO;
    private DataAlarmDAO dataAlarmDAO;
    private ConfigDataParamAlarmRelationDAO configDataParamAlarmRelationDAO;
    private ConfigDataParamAlgorithmParamRelationDAO paramRelationDAO;
    private DataAlgorithmDAO dataAlgorithmDAO;
    private DataAlgorithmFormulaConfigDAO dataAlgorithmFormulaConfigDAO;
    private DataAlgorithmParamConfigDAO dataAlgorithmParamConfigDAO;
    private DataLabelItemDAO dataLabelItemDAO;
    private DataAlgorithmScriptConfigDAO scriptConfigDAO;









//    /**
//     * 保存报警数据
//     *
//     * @param configDataParamManagementDTO
//     * @param configDataParamManagementDO
//     */
//    private void saveOrUpdateAlarmList(ConfigDataParamManagementDTO configDataParamManagementDTO,
//                                       ConfigDataParamManagementDO configDataParamManagementDO) {
//        dataAlarmDAO.delete(Wrappers.<DataAlarmDO>lambdaQuery().eq(DataAlarmDO::getDataParamId, configDataParamManagementDTO.getId()));
//
//        List<ConfigAlarmDTO> configAlarmDTOList = configDataParamManagementDTO.getConfigAlarmDTOList();
//        if (CollectionUtil.isEmpty(configAlarmDTOList)) {
//            return;
//        }
//        // 保存报警数据到报警表中
//        List<DataAlarmDO> dataAlarmIdList = new ArrayList<>();
//        configAlarmDTOList.forEach(configAlarmDTO -> {
//            DataAlarmDO dataAlarmDO = new DataAlarmDO();
//            dataAlarmDO.setCode(configDataParamManagementDTO.getCode());
//            dataAlarmDO.setName(configDataParamManagementDO.getName());
//            dataAlarmDO.setSource(configDataParamManagementDTO.getSource());
//            dataAlarmDO.setAlarmClass(configAlarmDTO.getAlarmClass());
//            dataAlarmDO.setAlarmDescribe(configAlarmDTO.getAlarmDescribe());
//            dataAlarmDO.setAlarmCondition(configAlarmDTO.getAlarmCondition());
//            dataAlarmDO.setAlarmName(configAlarmDTO.getAlarmName());
//            dataAlarmDO.setAlarmType(configAlarmDTO.getAlarmType());
//            dataAlarmDO.setDataParamId(configDataParamManagementDO.getId());
//            setCreateDefaultField(dataAlarmDO, configDataParamManagementDTO);
//            dataAlarmIdList.add(dataAlarmDO);
//        });
//        // 批量保存报警数据到报警表中
//        dataAlarmDAO.insertBatch(dataAlarmIdList);
//    }


    /**
     * 通过id查询变量管理数据
     *
     * @param id
     * @return
     */
    @Override
    public ConfigDataParamManagementDTO queryById(Long id) {
        // 查询变量管理的基础表信息
        ConfigDataParamManagementDO configDataParamManagementDO = dataParamManagementDAO
                .selectOne(Wrappers.<ConfigDataParamManagementDO>lambdaQuery()
                        .ne(ConfigDataParamManagementDO::getStatus, 9)
                        .eq(ConfigDataParamManagementDO::getId, id));
        ConfigDataParamManagementDTO configDataParamManagementDTO = BeanUtils.copyToObject(configDataParamManagementDO, ConfigDataParamManagementDTO.class);

        configDataParamManagementDTO.setConfigAlgorithDTO(mapAlgorithm(Collections.singletonList(id)).get(id));
//        configDataParamManagementDTO.setConfigLabelDTOList(mapConfigLabelList(Collections.singletonList(id)).get(id));
        configDataParamManagementDTO.setConfigParamDTOList(mapConfigParamList(Collections.singletonList(configDataParamManagementDTO)).get(id));
        configDataParamManagementDTO.setConfigAlarmDTOList(mapDataLabelList(Collections.singletonList(id)).get(id));

        return configDataParamManagementDTO;
    }

    @Override
    public List<ConfigDataParamManagementDTO> queryByName(String name) {
        List<ConfigDataParamManagementDO> configDataParamManagementDOList = dataParamManagementDAO
                .selectList(Wrappers.<ConfigDataParamManagementDO>lambdaQuery().eq(ConfigDataParamManagementDO::getStatus, 0)
                        .eq(ConfigDataParamManagementDO::getName, name));
        if (CollectionUtil.isEmpty(configDataParamManagementDOList)) {
            return CollUtil.newArrayList();
        }
        return BeanUtils.copyToList(configDataParamManagementDOList, ConfigDataParamManagementDTO.class);
    }


//
//    /**
//     * map 获取标签数据
//     *
//     * @param dataParamIds 数据参数 ID
//     * @return {@link Map}<{@link Long}, {@link List}<{@link ConfigLabelDTO}>>
//     */
//    private Map<Long, List<ConfigLabelDTO>> mapConfigLabelList(List<Long> dataParamIds) {
//        List<ConfigDataParamLabelRelationDO> relationList = dataParamLabelRelationDAO.selectList(Wrappers.<ConfigDataParamLabelRelationDO>lambdaQuery()
//                .in(ConfigDataParamLabelRelationDO::getDataParamId, dataParamIds));
//        // 没有数据
//        if (CollUtil.isEmpty(relationList)) {
//            return Collections.emptyMap();
//        }
//        Map<Long, List<Long>> mapRelation = relationList.stream().collect(Collectors.groupingBy(ConfigDataParamLabelRelationDO::getDataParamId,
//                Collectors.mapping(ConfigDataParamLabelRelationDO::getLableItemId, Collectors.toList())));
//
//        List<Long> labelItemIds = relationList.stream().map(ConfigDataParamLabelRelationDO::getLableItemId).collect(Collectors.toList());
//        List<DataLabelItemDO> labelItemList = dataLabelItemDAO.selectBatchIds(labelItemIds);
//        if (CollUtil.isEmpty(labelItemList)) {
//            return Collections.emptyMap();
//        }
//        Map<Long, DataLabelItemDO> mapLabel = labelItemList.stream().collect(Collectors.toMap(DataLabelItemDO::getId, item -> item));
//        Map<Long, List<ConfigLabelDTO>> result = new HashMap<>(mapRelation.size());
//
//        List<DataLabelItemRelationDO> dataLabelItemRelationDOS = dataLabelItemRelationDAO
//                .selectList(Wrappers.<DataLabelItemRelationDO>lambdaQuery()
//                        .in(DataLabelItemRelationDO::getLabelItemId, labelItemIds));
//        Map<Long, Long> relationDOMap = dataLabelItemRelationDOS.stream().collect(Collectors.toMap(DataLabelItemRelationDO::getLabelItemId, DataLabelItemRelationDO::getLabelId));
//
//        List<DataLabelDO> dataLabelList = dataLabelDAO.selectBatchIds(relationDOMap.values());
//        Map<Long, DataLabelDO> dataLabelDOMap = dataLabelList.stream().collect(Collectors.toMap(DataLabelDO::getId, item -> item));
//
//
//        for (Long key : mapRelation.keySet()) {
//            List<Long> dataLabelItemId = mapRelation.get(key);
//            List<ConfigLabelDTO> configLabelDTOList = new ArrayList<>();
//            for (Long labelItemId : dataLabelItemId) {
//                DataLabelItemDO dataLabelItemDO = mapLabel.get(labelItemId);
//                DataLabelDO dataLabelDO = dataLabelDOMap.get(relationDOMap.get(labelItemId));
//                configLabelDTOList.add(configLabelDTO(dataLabelItemDO, dataLabelDO));
//            }
//            result.put(key, configLabelDTOList);
//        }
//        return result;
//    }

    private ConfigLabelDTO configLabelDTO(DataLabelItemDO dataLabelItemDO, DataLabelDO dataLabelDOMap) {
        ConfigLabelDTO configLabelDTO = new ConfigLabelDTO();
        if(Objects.nonNull(dataLabelItemDO)){
            configLabelDTO.setLabelItemId(dataLabelItemDO.getId());
            configLabelDTO.setLabelItemName(dataLabelItemDO.getLabelItemName());
            configLabelDTO.setLabelItemPath(dataLabelItemDO.getItemPath());
        }
        if(Objects.nonNull(dataLabelDOMap)){
            configLabelDTO.setLabelName(dataLabelDOMap.getLabelName());
        }
        return configLabelDTO;
    }



    /**
     * map 获取算法数据
     *
     * @param dataParamIds 数据参数 ID
     * @return {@link Map}<{@link Long}, {@link ConfigAlgorithDTO}>
     */
    private Map<Long, ConfigAlgorithDTO> mapAlgorithm(List<Long> dataParamIds) {
        // todo 可能还有脚本的算法
        List<ConfigDataParamAlgorithmRelationDO> relationList = algorithmRelationDAO
                .selectList(Wrappers.<ConfigDataParamAlgorithmRelationDO>lambdaQuery()
                .in(ConfigDataParamAlgorithmRelationDO::getDataParamId, dataParamIds));
        // 没有数据
        if (CollUtil.isEmpty(relationList)) {
            return Collections.emptyMap();
        }
        // 1 : 1 key : dataParamId value : algorithmId
        Map<Long, Long> mapRelation = relationList.stream()
                .collect(Collectors
                        .toMap(ConfigDataParamAlgorithmRelationDO::getDataParamId,
                                ConfigDataParamAlgorithmRelationDO::getAlgorithmId));
        List<DataAlgorithmDO> algorithmList = dataAlgorithmDAO.selectBatchIds(mapRelation.values());
        if (CollUtil.isEmpty(algorithmList)) {
            return Collections.emptyMap();
        }
        Map<Long, DataAlgorithmDO> mapAlgorithm = algorithmList.stream().collect(Collectors.toMap(DataAlgorithmDO::getId, item -> item));


        List<Long> algorithmIds4Formula = new ArrayList<>();
        List<Long> algorithmIds4Script = new ArrayList<>();
        algorithmList.stream().forEach(item -> {
            if ("计算公式配置".equals(item.getConfigurationScheme())) {
                algorithmIds4Formula.add(item.getId());
            } else {
                algorithmIds4Script.add(item.getId());
            }
        });

        Map<Long, List<String>> formulaMap = new HashMap<>();
        if (CollUtil.isNotEmpty(algorithmIds4Formula)) {
            List<DataAlgorithmFormulaConfigDO> dataAlgorithmFormulaConfigDOS = dataAlgorithmFormulaConfigDAO.selectList(Wrappers.<DataAlgorithmFormulaConfigDO>lambdaQuery()
                    .in(DataAlgorithmFormulaConfigDO::getAlgorithmId, algorithmIds4Formula));
            formulaMap = dataAlgorithmFormulaConfigDOS.stream().collect(Collectors.groupingBy(DataAlgorithmFormulaConfigDO::getAlgorithmId,
                    Collectors.mapping(DataAlgorithmFormulaConfigDO::getFormula, Collectors.toList())));
        }

        Map<Long, List<DataAlgorithmScriptConfigDO>> scriptMap = new HashMap<>();
        if (CollUtil.isNotEmpty(algorithmIds4Script)) {
            List<DataAlgorithmScriptConfigDO> dataAlgorithmScriptConfigDOS = scriptConfigDAO.selectList(Wrappers.<DataAlgorithmScriptConfigDO>lambdaQuery()
                    .in(DataAlgorithmScriptConfigDO::getAlgorithmId, algorithmIds4Script));
            scriptMap = dataAlgorithmScriptConfigDOS.stream().collect(Collectors.groupingBy(DataAlgorithmScriptConfigDO::getAlgorithmId,
                    Collectors.mapping(item -> item, Collectors.toList())));
        }

        Map<Long, ConfigAlgorithDTO> result = new HashMap<>(mapRelation.size());
        Map<Long, List<DataAlgorithmScriptConfigDO>> finalScriptMap = scriptMap;
        Map<Long, List<String>> finalFormulaMap = formulaMap;
        dataParamIds.forEach(id -> {
            Long algorithmId = mapRelation.get(id);
            result.put(id, configAlgorithDTO(mapAlgorithm.getOrDefault(algorithmId, new DataAlgorithmDO()),
                    finalFormulaMap.getOrDefault(algorithmId, new ArrayList<>()),
                    finalScriptMap.getOrDefault(algorithmId, new ArrayList<>())));
        });
        return result;
    }

    private ConfigAlgorithDTO configAlgorithDTO(DataAlgorithmDO dataAlgorithmDO,
                                                List<String> formulaList,
                                                List<DataAlgorithmScriptConfigDO> scriptList) {
        ConfigAlgorithDTO configAlgorithDTO = new ConfigAlgorithDTO();
        configAlgorithDTO.setAlgorithId(dataAlgorithmDO.getId());
        configAlgorithDTO.setAlgorithName(dataAlgorithmDO.getName());
        configAlgorithDTO.setAlgorithmType(dataAlgorithmDO.getType());

        configAlgorithDTO.setAlgorithDescription(dataAlgorithmDO.getDescription());
        configAlgorithDTO.setAlgorithAccuracyDigit(dataAlgorithmDO.getAccuracyDigit());

        configAlgorithDTO.setAlgorithConfigurationScheme(dataAlgorithmDO.getConfigurationScheme());
        if ("计算公式配置".equals(dataAlgorithmDO.getConfigurationScheme())) {
            if (!formulaList.isEmpty()) {
                configAlgorithDTO.setAlgorithFormula(formulaList.get(0));
            }
        } else {
            if (!scriptList.isEmpty()) {
                DataAlgorithmScriptConfigDO dataAlgorithmScriptConfigDO = scriptList.get(0);
                Optional.ofNullable(dataAlgorithmScriptConfigDO).ifPresent(item -> {
                    configAlgorithDTO.setScriptPath(item.getScriptPath());
                    configAlgorithDTO.setRequestType(item.getRequestType());
                });
            }
        }
        return configAlgorithDTO;
    }

    /**
     * map 获取算法参数数据
     *
     * @param dataParamManagementDTOList 数据参数 ID
     * @return {@link Map}<{@link Long}, {@link List}<{@link ConfigParamDTO}>>
     */
    private Map<Long, List<ConfigParamDTO>> mapConfigParamList(List<ConfigDataParamManagementDTO> dataParamManagementDTOList) {
        List<Long> dataParamIds = dataParamManagementDTOList.stream().map(ConfigDataParamManagementDTO::getId).collect(Collectors.toList());

        List<ConfigDataParamAlgorithmRelationDO> relationList = algorithmRelationDAO
                .selectList(Wrappers.<ConfigDataParamAlgorithmRelationDO>lambdaQuery()
                        .in(ConfigDataParamAlgorithmRelationDO::getDataParamId, dataParamIds));
        // 没有数据
        if (CollUtil.isEmpty(relationList)) {
            return Collections.emptyMap();
        }
        // 1 : 1 map key : dataParamId value : algorithmId
        Map<Long, Long> mapRelation = relationList.stream().collect(Collectors.toMap(ConfigDataParamAlgorithmRelationDO::getDataParamId, ConfigDataParamAlgorithmRelationDO::getAlgorithmId));

        // 所有算法参数关联
        List<DataAlgorithmFormulaConfigDO> dataAlgorithmFormulaConfigDOS = dataAlgorithmFormulaConfigDAO.selectList(Wrappers.<DataAlgorithmFormulaConfigDO>lambdaQuery()
                .in(DataAlgorithmFormulaConfigDO::getAlgorithmId, mapRelation.values()));

        if (CollUtil.isEmpty(dataAlgorithmFormulaConfigDOS)) {
            return Collections.emptyMap();
        }
        // map key : 算法id value : 参数ids
        Map<Long, List<Long>> mapParamList = dataAlgorithmFormulaConfigDOS.stream()
                .collect(Collectors.groupingBy(DataAlgorithmFormulaConfigDO::getAlgorithmId,
                        Collectors.mapping(DataAlgorithmFormulaConfigDO::getAlgorithmParamId, Collectors.toList())));
        // list 参数ids
        List<Long> algorithmParamIdList = dataAlgorithmFormulaConfigDOS.stream().map(DataAlgorithmFormulaConfigDO::getAlgorithmParamId).collect(Collectors.toList());
        List<DataAlgorithmParamConfigDO> dataAlgorithmParamConfigList = dataAlgorithmParamConfigDAO.selectBatchIds(algorithmParamIdList);

        List<ConfigDataParamAlgorithmParamRelationDO> paramDataParamRelationList = paramRelationDAO.selectList(Wrappers.<ConfigDataParamAlgorithmParamRelationDO>lambdaQuery()
                .in(ConfigDataParamAlgorithmParamRelationDO::getAlgorithParamId, algorithmParamIdList)
                .isNotNull(ConfigDataParamAlgorithmParamRelationDO::getDataParamId)
                .isNotNull(ConfigDataParamAlgorithmParamRelationDO::getParentParamId));
        Map<String, ConfigDataParamManagementDO> dataParamManagementMap = new HashMap<>();
        if (CollUtil.isNotEmpty(paramDataParamRelationList)) {
            // map key : 算法参数id_dataParamParentId  value : dataParamId
            Map<String, Long> tempMap = paramDataParamRelationList.stream().collect(Collectors.toMap(item -> item.getAlgorithParamId() + "_" + item.getParentParamId(), ConfigDataParamAlgorithmParamRelationDO::getDataParamId));
            // 被关联的dataParamIds
            Collection<Long> bindDataParamIds = tempMap.values();
            List<ConfigDataParamManagementDO> dataParamManagementDOS = dataParamManagementDAO.selectBatchIds(bindDataParamIds);
            Map<Long, ConfigDataParamManagementDO> collect = dataParamManagementDOS.stream().collect(Collectors.toMap(ConfigDataParamManagementDO::getId, item -> item));
            for (String key : tempMap.keySet()) {
                Long dataParamId = tempMap.get(key);
                ConfigDataParamManagementDO configDataParamManagementDO = collect.get(dataParamId);
                dataParamManagementMap.put(key, configDataParamManagementDO);
            }
        }


        if (CollUtil.isEmpty(dataAlgorithmParamConfigList)) {
            return Collections.emptyMap();
        }
        // map key : 参数id value : 参数
        Map<Long, DataAlgorithmParamConfigDO> mapParam = dataAlgorithmParamConfigList.stream()
                .collect(Collectors.toMap(DataAlgorithmParamConfigDO::getId, item -> item));

        Map<Long, List<ConfigParamDTO>> result = new HashMap<>(mapRelation.size());
        dataParamManagementDTOList.forEach(dataParam -> {
            Long id = dataParam.getId();
            Long algorithmId = mapRelation.get(id);
            List<Long> paramIds = mapParamList.get(algorithmId);
            if (CollUtil.isNotEmpty(paramIds)) {
                List<ConfigParamDTO> configParamDTOList = paramIds.stream()
                        .map(mapParam::get)
                        .map(item -> configParamDTO(item, dataParamManagementMap, id))
                        .collect(Collectors.toList());
                result.put(id, configParamDTOList);
            }
        });

        return result;
    }

    private ConfigParamDTO configParamDTO(DataAlgorithmParamConfigDO dataAlgorithmParamConfigDO,
                                          Map<String, ConfigDataParamManagementDO> dataParamManagementMap,
                                          Long paramId) {
        ConfigParamDTO configParamDTO = new ConfigParamDTO();
        if(Objects.isNull(dataAlgorithmParamConfigDO)){
            return configParamDTO;
        }
        configParamDTO.setParamId(dataAlgorithmParamConfigDO.getId());
        configParamDTO.setParamSign(dataAlgorithmParamConfigDO.getMark());
        configParamDTO.setParamdesc(dataAlgorithmParamConfigDO.getDescription());
        configParamDTO.setParamType(dataAlgorithmParamConfigDO.getMappedType());
        if (ALGORITHM_TYPE_FORMULA.equals(configParamDTO.getParamType())) {
            ConfigDataParamManagementDO bindInfo = dataParamManagementMap
                    .getOrDefault(dataAlgorithmParamConfigDO.getId() + StrUtil.UNDERLINE + paramId, new ConfigDataParamManagementDO());
            if (ObjectUtil.isNotEmpty(bindInfo)) {
                configParamDTO.setVariableId(bindInfo.getId());
                configParamDTO.setVariableValue(bindInfo.getCode());
                configParamDTO.setVariableDeclaration(bindInfo.getName());
            }
        } else {
            configParamDTO.setVariableValue(dataAlgorithmParamConfigDO.getGlobalVariableValue());
            configParamDTO.setVariableDeclaration(dataAlgorithmParamConfigDO.getGlobalVariableDescription());
        }
        return configParamDTO;
    }

    /**
     * map 获取警告数据
     *
     * @param dataParamIds 数据参数 ID
     * @return {@link Map}<{@link Long}, {@link List}<{@link ConfigAlarmDTO}>>
     */
    private Map<Long, List<ConfigAlarmDTO>> mapDataLabelList(List<Long> dataParamIds) {
        List<DataAlarmDO> dataAlarmDOS = dataAlarmDAO.selectList(Wrappers.<DataAlarmDO>lambdaQuery()
                .in(DataAlarmDO::getDataParamId, dataParamIds));
        if (CollUtil.isEmpty(dataAlarmDOS)) {
            return Collections.emptyMap();
        }

        Map<Long, List<DataAlarmDO>> collect = dataAlarmDOS.stream().collect(Collectors.groupingBy(DataAlarmDO::getDataParamId));
        return collect.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> {
            List<DataAlarmDO> value = entry.getValue();
            return BeanUtils.copyToList(value, ConfigAlarmDTO.class);
        }));
    }


    /**
     * 更新数据
     *
     * @param configDataParamManagementDTO
     * @return
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ConfigDataParamManagementDTO update(ConfigDataParamManagementDTO configDataParamManagementDTO) throws ServiceException {
        // 查询原本信息
        ConfigDataParamManagementDO existDataParamManagementDO = dataParamManagementDAO.selectById(configDataParamManagementDTO.getId());
        // 第一步：更新基本信息
        ConfigDataParamManagementDO configDataParamManagementDO = BeanUtils.copyToObject(configDataParamManagementDTO, ConfigDataParamManagementDO.class);
        dataParamManagementDAO.updateById(configDataParamManagementDO);

        // 更新标签信息
//        saveOrUpdateLabelList(configDataParamManagementDTO, existDataParamManagementDO.getId());
        // 更新算法和参数依赖
        saveOrUpdateAlgorithm(configDataParamManagementDTO, existDataParamManagementDO.getId());
        // 更新报警信息
        saveOrUpdateAlarmList(configDataParamManagementDTO, configDataParamManagementDO);
        return configDataParamManagementDTO;
    }

    public void saveOrUpdateAlarmList(ConfigDataParamManagementDTO configDataParamManagementDTO,
                                      ConfigDataParamManagementDO configDataParamManagementDO) {
        dataAlarmDAO.delete(Wrappers.<com.jtny.nytb.config.dataalarm.domain.DataAlarmDO>lambdaQuery().eq(DataAlarmDO::getDataParamId, configDataParamManagementDTO.getId()));

        List<ConfigAlarmDTO> configAlarmDTOList = configDataParamManagementDTO.getConfigAlarmDTOList();
        if (CollectionUtil.isEmpty(configAlarmDTOList)) {
            return;
        }
        // 保存报警数据到报警表中
        List<com.jtny.nytb.config.dataalarm.domain.DataAlarmDO> dataAlarmIdList = new ArrayList<>();
        configAlarmDTOList.forEach(configAlarmDTO -> {
            com.jtny.nytb.config.dataalarm.domain.DataAlarmDO dataAlarmDO = new com.jtny.nytb.config.dataalarm.domain.DataAlarmDO();
            dataAlarmDO.setCode(configDataParamManagementDTO.getCode());
            dataAlarmDO.setName(configDataParamManagementDO.getName());
            dataAlarmDO.setSource(configDataParamManagementDTO.getSource());
            dataAlarmDO.setAlarmClass(configAlarmDTO.getAlarmClass());
            dataAlarmDO.setAlarmDescribe(configAlarmDTO.getAlarmDescribe());
            dataAlarmDO.setAlarmCondition(configAlarmDTO.getAlarmCondition());
            dataAlarmDO.setAlarmName(configAlarmDTO.getAlarmName());
            dataAlarmDO.setAlarmType(configAlarmDTO.getAlarmType());
            dataAlarmDO.setDataParamId(configDataParamManagementDO.getId());
            dataAlarmIdList.add(dataAlarmDO);
        });
        // 批量保存报警数据到报警表中
        dataAlarmDAO.insertBatch(dataAlarmIdList);
    }

    public void saveOrUpdateAlgorithm(ConfigDataParamManagementDTO configDataParamManagementDTO, Long manageId) {
        // 删除上次的关联关系
        algorithmRelationDAO.delete(Wrappers.<ConfigDataParamAlgorithmRelationDO>lambdaQuery()
                .eq(ConfigDataParamAlgorithmRelationDO::getDataParamId, manageId));
        // 插入数据变量算法依赖
        if (configDataParamManagementDTO.getAlgorithmId() != null) {
            ConfigDataParamAlgorithmRelationDO configDataParamAlgorithmRelationDO = new ConfigDataParamAlgorithmRelationDO();
            configDataParamAlgorithmRelationDO.setDataParamId(manageId);
            configDataParamAlgorithmRelationDO.setAlgorithmId(configDataParamManagementDTO.getAlgorithmId());
            algorithmRelationDAO.insert(configDataParamAlgorithmRelationDO);
        }
        // 更新参数参量对应数据
        saveOrUpdateParamList(configDataParamManagementDTO);
    }
//    public void saveOrUpdateLabelList(ConfigDataParamManagementDTO configDataParamManagementDTO, Long dataParamId) {
//        // 删除上次的关联关系
//        dataParamLabelRelationDAO.delete(Wrappers.<ConfigDataParamLabelRelationDO>lambdaQuery()
//                .eq(ConfigDataParamLabelRelationDO::getDataParamId, dataParamId));
//        // 插入数据标签依赖
//        List<ConfigLabelDTO> configLabelDTOList = configDataParamManagementDTO.getConfigLabelDTOList();
//        // 防止空指针
//        configLabelDTOList = CollectionUtil.isEmpty(configLabelDTOList) ? new ArrayList<>() : configLabelDTOList;
//
//        List<ConfigDataParamLabelRelationDO> labelRelationList = new ArrayList<>();
//        configLabelDTOList.forEach(configLabelDTO -> {
//            ConfigDataParamLabelRelationDO configDataParamLabelRelationDO = new ConfigDataParamLabelRelationDO();
//            configDataParamLabelRelationDO.setLableItemId(configLabelDTO.getLabelItemId());
//            configDataParamLabelRelationDO.setDataParamId(dataParamId);
//            labelRelationList.add(configDataParamLabelRelationDO);
//        });
//        // add 默认统一标识标签
//        addUnifiedIdentifierLabel(labelRelationList, configDataParamManagementDTO.getUnifiedIdentifierName(), dataParamId);
//        if (CollectionUtil.isEmpty(labelRelationList)) {
//            return;
//        }
//        dataParamLabelRelationDAO.insertBatch(labelRelationList);
//    }
    private void addUnifiedIdentifierLabel(List<ConfigDataParamLabelRelationDO> labelRelationList,
                                           String unifiedIdentifierName, Long dataParamId) {
        DataLabelItemDO dataLabelItemDO = dataLabelItemDAO.selectOne(Wrappers.<DataLabelItemDO>lambdaQuery()
                .eq(DataLabelItemDO::getLabelItemName, unifiedIdentifierName)
                .last("limit 1"));
        if (ObjectUtil.isNotNull(dataLabelItemDO)) {
            Long id = dataLabelItemDO.getId();
            List<ConfigDataParamLabelRelationDO> temp = labelRelationList.stream()
                    .filter(item -> item.getLableItemId().equals(id))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(temp)) {
                return;
            }
            ConfigDataParamLabelRelationDO labelRelation = new ConfigDataParamLabelRelationDO();
            labelRelation.setLableItemId(dataLabelItemDO.getId());
            labelRelation.setDataParamId(dataParamId);
            labelRelationList.add(labelRelation);
        }
    }

    private void saveOrUpdateParamList(ConfigDataParamManagementDTO configDataParamManagementDTO) {
        Long id = configDataParamManagementDTO.getId();
        Assert.notNull(id, "参量id不能为空");

        paramRelationDAO.delete(Wrappers.<ConfigDataParamAlgorithmParamRelationDO>lambdaQuery()
                .eq(ConfigDataParamAlgorithmParamRelationDO::getParentParamId, id));
//        deleteLastParamRelation(configDataParamAlgorithmRelationDO, configDataParamManagementDTO.getId());
        // 判定当前有没有需要插入的参数数据，如果没有则返回。
        List<ConfigParamDTO> configParamDTOList = configDataParamManagementDTO.getConfigParamDTOList();
        if (CollectionUtil.isEmpty(configParamDTOList)) {
            return;
        }
        List<ConfigDataParamAlgorithmParamRelationDO> dataAlgorithParamRelationDOList = new ArrayList<>();
        configParamDTOList.forEach(configParamDTO -> {
            // 剔除 全局变量
            if ("全局变量".equals(configParamDTO.getParamType())) {
                return;
            }
            ConfigDataParamAlgorithmParamRelationDO configDataParamAlgorithmParamRelationDO = new ConfigDataParamAlgorithmParamRelationDO();
            configDataParamAlgorithmParamRelationDO.setAlgorithParamId(configParamDTO.getParamId());
            configDataParamAlgorithmParamRelationDO.setDataParamId(configParamDTO.getVariableId());
            configDataParamAlgorithmParamRelationDO.setParentParamId(id);
            dataAlgorithParamRelationDOList.add(configDataParamAlgorithmParamRelationDO);
        });
        if (CollectionUtil.isEmpty(dataAlgorithParamRelationDOList)) {
            return;
        }
        paramRelationDAO.insertBatch(dataAlgorithParamRelationDOList);
    }


    /**
     * 通过id进行删除数据
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ConfigDataParamManagementDTO deleteById(Long id) {
        // 删除基本信息
        ConfigDataParamManagementDO paramManagementDO = dataParamManagementDAO.selectById(id);
        paramManagementDO.setStatus(9);
        dataParamManagementDAO.updateById(paramManagementDO);
        ConfigDataParamManagementDTO paramManagementDTO = BeanUtils.copyToObject(paramManagementDO, ConfigDataParamManagementDTO.class);
        // 删除警告
        deleteAlarmByParamId(id);

        // 删除标签
//        QueryWrapper<ConfigDataParamLabelRelationDO> labelRelationDAOQueryWrapper = new QueryWrapper<>();
//        labelRelationDAOQueryWrapper.eq("data_param_id", id);
//        dataParamLabelRelationDAO.delete(labelRelationDAOQueryWrapper);

        // 删除公式和参数
        deleteAlgorithmByParamId(id);

        return paramManagementDTO;
    }

    /**
     * 按 ID 列表删除
     *
     * @param ids IDS
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deleteByIdList(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return;
        }
        ids.forEach(this::deleteById);
    }






    /**
     * 地图代码和 ID 保存批次
     *
     * @param list 管理 dtolist
     * @return {@link Map}<{@link String}, {@link Long}>
     */
    @Override
    public Map<String, Long> mapCodeAndIdSaveBatch(List<ConfigDataParamManagementDTO> list) {
        List<ConfigDataParamManagementDTO> collect = list.stream().map(this::save).collect(Collectors.toList());
        return collect.stream().collect(Collectors.toMap(ConfigDataParamManagementDTO::getCode, ConfigDataParamManagementDTO::getId));
    }

    @Override
    public List<ConfigDataParamManagementDTO> downloadManagement() {
        QueryWrapper<ConfigDataParamManagementDO> managementWrapper = new QueryWrapper<>();
        managementWrapper.eq("status", 0);
        List<ConfigDataParamManagementDO> configDataParamManagementDOS = dataParamManagementDAO.selectList(managementWrapper);
        List<ConfigDataParamManagementDTO> paramManagementList = BeanUtils.copyToList(configDataParamManagementDOS, ConfigDataParamManagementDTO.class);
        return paramManagementList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importParamAndAlgorit(Map<String, List<?>> importData)  {
        //设备模型参量
        List<ConfigDataParamManagementDO> configDataParamManagementDOs =
                BeanUtils.copyToList(importData.get(EXCEL_DATA_PARAM_VO), ConfigDataParamManagementDO.class);

        //参量频率
        List<ExcelFrequencyDTO> excelFrequencyDTOS =
                BeanUtils.copyToList(importData.get(EXCEL_FREQUENCY_VO), ExcelFrequencyDTO.class);
        //算法
        List<AlgorithmExcelDTO> algorithmExcelDTOs =
                BeanUtils.copyToList(importData.get(ALGORITHM_EXCEL_VO), AlgorithmExcelDTO.class);
        //算法参数
        List<ExcelAlgorithmParamDTO> excelAlgorithmParamDTOs =
                BeanUtils.copyToList(importData.get(EXCEL_ALGORITHM_PARAM_VO), ExcelAlgorithmParamDTO.class);
        //参量标签
        List<ExcelLabelDTO> excelLabelDTOs =
                BeanUtils.copyToList(importData.get(EXCEL_LABEL_VO), ExcelLabelDTO.class);
        //设备告警
        List<ExcelAlarmDTO> excelAlarmDTOs =
                BeanUtils.copyToList(importData.get(EXCEL_ALARM_VO), ExcelAlarmDTO.class);

        if(CollectionUtils.isEmpty(configDataParamManagementDOs)){
            return;
        }

        //校验重复
        checkDup(configDataParamManagementDOs);

        //设置来源
        configDataParamManagementDOs.forEach(ConfigDataParamManagementDO::setSourceInteger);

        //参量基础表
        initParamManager(configDataParamManagementDOs, excelFrequencyDTOS, algorithmExcelDTOs);

        //name id  参量表
        QueryWrapper<ConfigDataParamManagementDO> configDataParamManagementDOQueryWrapper = new QueryWrapper<>();
        configDataParamManagementDOQueryWrapper.lambda().eq(ConfigDataParamManagementDO::getStatus,0);
        List<ConfigDataParamManagementDO> listParam = this.list(configDataParamManagementDOQueryWrapper);
        Map<String, Long> dataParamMapByName =
                listParam.stream().collect(Collectors.toMap(k -> k.getName(), k -> k.getId()));

        //算法保存
        Map<String, Long> algorithmMapByName = initAlgorit(algorithmExcelDTOs, dataParamMapByName);

        //算法参量关系
        initParamRealtion(excelAlgorithmParamDTOs, dataParamMapByName, algorithmMapByName);



        //警报
        initAlarm(excelAlarmDTOs, listParam);
    }

    private CodeRuleProperty codeRuleProperty;
    private ConfigRuleManagementServiceImpl configRuleManagementServiceImpl;
    public void initParamManager(List<ConfigDataParamManagementDO> configDataParamManagementDOs, List<ExcelFrequencyDTO> excelFrequencyDTOS, List<AlgorithmExcelDTO> algorithmExcelDTOs) {
        //设置编码
        configDataParamManagementDOs.forEach(e-> e.setCode(configRuleManagementServiceImpl.queryCodeBycode(codeRuleProperty.getDataParamCodeRule(),"")));
        this.saveBatch(configDataParamManagementDOs,500);

        //参量来源：设备采集 设置频率
        configDataParamManagementDOs.parallelStream()
                .filter(e->e.getSource() == ConfigDataParamManagementDO.DEVICE_ACQ)
                .forEach(e->{
                    List<ExcelFrequencyDTO> excelFrequencyDTO =
                            excelFrequencyDTOS.stream().filter(son -> son.getDataParamName().equals(e.getName())).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(excelFrequencyDTO)){
                        ExcelFrequencyDTO frequency = excelFrequencyDTO.get(0);
                        e.setFrequency(frequency.getFrequency());
                        e.setFrequencyUnit(frequency.getFrequencyUnit());
                    }
                });


        //参量来源：系统生成 设置频率 和算法名称
        configDataParamManagementDOs.parallelStream()
                .filter(e->e.getSource() == ConfigDataParamManagementDO.SYSTEM_CAL)
                .forEach(e->{
                    List<AlgorithmExcelDTO> algorithms =
                            algorithmExcelDTOs.stream().filter(son -> son.getDataParamName().equals(e.getName())).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(algorithms)){
                        AlgorithmExcelDTO algorithmExcelDTO = algorithms.get(0);
                        e.setFrequency(algorithmExcelDTO.getFrequency());
                        e.setFrequencyUnit(algorithmExcelDTO.getFrequencyUnit());
                        e.setAlgorithmName(algorithmExcelDTO.getAlgorithmName());
                    }
                });
        //设置参量频率和算法名称
        saveOrUpdateBatch(configDataParamManagementDOs);
    }
    private DataAlgorithmServiceImpl dataAlgorithmServiceImpl;
    @NotNull
    public Map<String, Long> initAlgorit(List<AlgorithmExcelDTO> algorithmExcelDTOs, Map<String, Long> dataParamMapByName) {
        if(CollectionUtils.isEmpty(algorithmExcelDTOs)){
            return null;
        }

        Set<String> algoritNames = algorithmExcelDTOs.stream().map(AlgorithmExcelDTO::getAlgorithmName).collect(Collectors.toSet());
        QueryWrapper<DataAlgorithmDO> dataAlgorithmDOQueryWrapper = new QueryWrapper<>();
        dataAlgorithmDOQueryWrapper.lambda()
                .in(CollectionUtils.isNotEmpty(algoritNames),DataAlgorithmDO::getName,algoritNames)
                .eq(DataAlgorithmDO::getStatus,0);
        List<DataAlgorithmDO> algorithms = dataAlgorithmServiceImpl.list(dataAlgorithmDOQueryWrapper);
        if(CollectionUtils.isEmpty(algorithms)){
            return null;
        }
        //name id
        Map<String, Long> algorithmMapByName =
                algorithms.stream().collect(Collectors.toMap(k -> k.getName(), k -> k.getId()));

        ArrayList<ConfigDataParamAlgorithmRelationDO> configDataParamAlgorithmRelationDOS = new ArrayList<>();
        algorithmExcelDTOs.forEach(e->{
            ConfigDataParamAlgorithmRelationDO configDataParamAlgorithmRelationDO = new ConfigDataParamAlgorithmRelationDO();
            Long paramId = dataParamMapByName.get(e.getDataParamName());
            Long algoritId = algorithmMapByName.get(e.getAlgorithmName());
            if(Objects.nonNull(paramId) && Objects.nonNull(algoritId)){
                configDataParamAlgorithmRelationDO.setDataParamId(paramId);
                configDataParamAlgorithmRelationDO.setAlgorithmId(algoritId);
                configDataParamAlgorithmRelationDOS.add(configDataParamAlgorithmRelationDO);
            }
        });
        algorithmRelationDAO.insertBatch(configDataParamAlgorithmRelationDOS);
        return algorithmMapByName;
    }
    @Override
    public ConfigDataParamManagementDTO save(ConfigDataParamManagementDTO configDataParamManagementDTO) throws ServiceException {
        Assert.notNull(configDataParamManagementDTO, "数据参量数据异常");
        Assert.notNull(configDataParamManagementDTO.getCode(), "数据参量数据异常");
        // 插入数据变量管理的基础信息
        ConfigDataParamManagementDO configDataParamManagementDO = BeanUtils.copyToObject(configDataParamManagementDTO, ConfigDataParamManagementDO.class);
        dataParamManagementDAO.insert(configDataParamManagementDO);
        // 设置id
        configDataParamManagementDTO.setId(configDataParamManagementDO.getId());

        // 插入数据变量算法依赖和参数依赖
        saveOrUpdateAlgorithm(configDataParamManagementDTO, configDataParamManagementDO.getId());
        // 插入数据标签依赖
//        saveOrUpdateLabelList(configDataParamManagementDTO, configDataParamManagementDO.getId());
        // 插入报警点数据
        saveOrUpdateAlarmList(configDataParamManagementDTO, configDataParamManagementDO);
        // 返回值摄入id
        configDataParamManagementDTO.setId(configDataParamManagementDO.getId());
        return configDataParamManagementDTO;
    }

    @Override
    public PageData<ConfigDataParamManagementDTO> queryPage(ConfigDataParamManagementPageDTO paramManagementPageDTO) {
        // 刷选如果含有算法的id，
        List<Long> findManageIdList = new ArrayList<>();
        if (paramManagementPageDTO.getAlgorithmId() != null && paramManagementPageDTO.getAlgorithmId() != 0) {
            QueryWrapper<ConfigDataParamAlgorithmRelationDO> wrapper = new QueryWrapper<>();
            wrapper.eq("algorithm_id", paramManagementPageDTO.getAlgorithmId());
            List<ConfigDataParamAlgorithmRelationDO> configDataParamAlgorithmRelationDOList = algorithmRelationDAO.selectList(wrapper);
            if (CollectionUtil.isEmpty(configDataParamAlgorithmRelationDOList)) {
                return new PageData<ConfigDataParamManagementDTO>();
            }
            List<Long> params = configDataParamAlgorithmRelationDOList.stream().map(ConfigDataParamAlgorithmRelationDO::getDataParamId).collect(Collectors.toList());
            findManageIdList.addAll(params);
        }
        /*// 筛选含有标签id
        if (CollectionUtil.isNotEmpty(paramManagementPageDTO.getLabelIdList())) {
            QueryWrapper<ConfigDataParamLabelRelationDO> labelRelationDOQueryWrapper = new QueryWrapper<>();
            labelRelationDOQueryWrapper.in("label_item_id", paramManagementPageDTO.getLabelIdList());
            List<ConfigDataParamLabelRelationDO> configDataParamLabelRelationDOList = dataParamLabelRelationDAO.selectList(labelRelationDOQueryWrapper);
            if (CollectionUtil.isEmpty(configDataParamLabelRelationDOList)) {
                return new PageData<ConfigDataParamManagementDTO>();
            }
            List<Long> params = configDataParamLabelRelationDOList.stream().map(ConfigDataParamLabelRelationDO::getDataParamId).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(findManageIdList)) {
                findManageIdList.addAll(params);
            } else {
                List<Long> ids = findManageIdList.stream().filter(obj -> params.contains(obj)).collect(Collectors.toList());
                if (CollectionUtil.isEmpty(ids)) {
                    return new PageData<>();
                }
                findManageIdList = ids;
            }
        }*/
        // 筛选数据
        if (CollUtil.isEmpty(findManageIdList)){
            PageData<ConfigDataParamManagementDO> managementPage = dataParamManagement(paramManagementPageDTO);
            PageData<ConfigDataParamManagementDTO> configDataParamManagementDTOPageData = managementPage.transformData(ConfigDataParamManagementDTO.class);
            return configDataParamManagementDTOPageData;
        }
        PageData<ConfigDataParamManagementDO> managementPage = pageManagement(paramManagementPageDTO, findManageIdList);
        PageData<ConfigDataParamManagementDTO> configDataParamManagementDTOPageData = managementPage.transformData(ConfigDataParamManagementDTO.class);
        Collection<ConfigDataParamManagementDTO> data = configDataParamManagementDTOPageData.getData();
        if (CollectionUtil.isEmpty(data)) {
            return configDataParamManagementDTOPageData;
        }
        // 配置标签数据
        //setLabelDataList(data);
        return configDataParamManagementDTOPageData;
    }


    /**
     * 通过标签id获取参量数据
     *
     * @param dataParamManagementQueryDTO 标签列表
     * @return
     */
//    @Override
//    public List<ConfigDataParamManagementDTO> queryParamByLabelIdList(DataParamManagementQueryDTO dataParamManagementQueryDTO) {
//        if (CollectionUtil.isEmpty(dataParamManagementQueryDTO.getLabelIdList())) {
//            throw new ServiceException(ConfigDataParamErrorCodeEnum.PARAM_LABEL_IDS_IS_NULL.getErrorCode(), ConfigDataParamErrorCodeEnum.PARAM_LABEL_IDS_IS_NULL.getErrorMessage());
//        }
//        // 查询标签参量列表，
//        QueryWrapper<ConfigDataParamLabelRelationDO> labelWrapper = new QueryWrapper<>();
//        labelWrapper.in("label_item_id", dataParamManagementQueryDTO.getLabelIdList());
//        List<ConfigDataParamLabelRelationDO> labelRelationDOList = dataParamLabelRelationDAO.selectList(labelWrapper);
//        if (CollectionUtil.isEmpty(labelRelationDOList)) {
//            return new ArrayList<>();
//        }
//        // 获取标签项对应参量id
//        List<Long> allparamIdList = labelRelationDOList.stream().map(ConfigDataParamLabelRelationDO::getDataParamId).distinct().collect(Collectors.toList());
//
//        List<DataLabelItemRelationDO> dataLabelItemRelations = dataLabelItemRelationDAO.selectList(Wrappers
//                .<DataLabelItemRelationDO>lambdaQuery()
//                .in(DataLabelItemRelationDO::getLabelItemId, dataParamManagementQueryDTO.getLabelIdList()));
//
//        Map<Long, List<DataLabelItemRelationDO>> labelItemMap = dataLabelItemRelations.stream()
//                .filter(obj -> obj.getLabelId() != null && obj.getLabelItemId() != null)
//                .collect(Collectors.groupingBy(DataLabelItemRelationDO::getLabelId));
//        for (Long key: labelItemMap.keySet()) {
//            List<DataLabelItemRelationDO> findLabelRelations = labelItemMap.get(key);
//            List<Long> labelIds = findLabelRelations.stream().map(DataLabelItemRelationDO::getLabelItemId).collect(Collectors.toList());
//            List<ConfigDataParamLabelRelationDO> labelRelationDOList1 = dataParamLabelRelationDAO.selectList(Wrappers
//                    .<ConfigDataParamLabelRelationDO>lambdaQuery()
//                    .in(ConfigDataParamLabelRelationDO::getLableItemId, labelIds)
//                    .select(ConfigDataParamLabelRelationDO::getDataParamId));
//            if (CollectionUtil.isEmpty(labelRelationDOList1)) {
//                return new ArrayList<>();
//            }
//            // 获取标签项对应参量id
//            List<Long> paramIdList = labelRelationDOList1.stream().map(ConfigDataParamLabelRelationDO::getDataParamId).distinct().collect(Collectors.toList());
//            List<Long> resultList = allparamIdList.stream().filter(paramIdList::contains).collect(Collectors.toList());
//            allparamIdList = resultList;
//        }
//        List<Long> distinctIds = allparamIdList.stream().distinct().collect(Collectors.toList());
//        // 获取参量数据。
//        QueryWrapper<ConfigDataParamManagementDO> managementWrapper = new QueryWrapper<>();
//        managementWrapper.eq("status", 0);
//        managementWrapper.in("id", distinctIds);
//        Optional.ofNullable(dataParamManagementQueryDTO.getFactorName())
//                .ifPresent(name -> managementWrapper.eq("name", name));
////        managementWrapper.like("name", dataParamManagementQueryDTO.getFactorName());
//        List<ConfigDataParamManagementDO> managementDOList = dataParamManagementDAO.selectList(managementWrapper);
//        List<ConfigDataParamManagementDTO> managementDTOList = BeanUtils.copyToList(managementDOList, ConfigDataParamManagementDTO.class);
//        return managementDTOList;
//    }

    /**
     * 查询参量数量
     *
     * @return {@link Long}
     */
    @Override
    public Long countAll() {
        return dataParamManagementDAO.selectCount(Wrappers.<ConfigDataParamManagementDO>lambdaQuery()
                .eq(ConfigDataParamManagementDO::getStatus, GenericStatusEnum.NORMAL.getValue()));
    }

    /**
     * 列表切割
     *
     * @param offset 抵消
     * @param limit  限制
     * @return {@link List}<{@link ConfigDataParamManagementDTO}>
     */
    @Override
    public List<ConfigDataParamManagementDTO> listCut(Long offset, Long limit) {
        LambdaQueryWrapper<ConfigDataParamManagementDO> wrapper = Wrappers.<ConfigDataParamManagementDO>lambdaQuery()
                .eq(ConfigDataParamManagementDO::getStatus, GenericStatusEnum.NORMAL.getValue());
        wrapper.orderByAsc(ConfigDataParamManagementDO::getId);
        if (offset!= null && limit!= null) {
            wrapper.last("limit " + limit + " offset " + offset);
        }
        return listByWrappers(wrapper);
    }

    /**
     * 通过时间查询参量
     *
     * @param time 开始时间
     * @return {@link List}<{@link ConfigDataParamManagementDTO}>
     */
    @Override
    public List<ConfigDataParamManagementDTO> listByCreateTime(Long time) {
        LambdaQueryWrapper<ConfigDataParamManagementDO> wrapper = Wrappers.<ConfigDataParamManagementDO>lambdaQuery()
                .gt(ConfigDataParamManagementDO::getCreateTime, time);
        return listByWrappers(wrapper);
    }



    @Override
    public List<ConfigDataParamManagementDTO> listByUpdateTime(Long time) {
        LambdaQueryWrapper<ConfigDataParamManagementDO> wrapper = Wrappers.<ConfigDataParamManagementDO>lambdaQuery()
                .gt(ConfigDataParamManagementDO::getLastUpdateTime, time);
        wrapper.eq(ConfigDataParamManagementDO::getStatus, GenericStatusEnum.NORMAL.getValue());
//        wrapper.last("limit 500 offset " + );
        return listByWrappers(wrapper);
    }

    /**
     * 按 ID 列出
     *
     * @param dataParamIds 数据参数 ID
     * @return {@link List}<{@link ConfigDataParamManagementDTO}>
     */
    @Override
    public List<ConfigDataParamManagementDTO> listByIds(List<Long> dataParamIds) {
        List<ConfigDataParamManagementDO> configDataParamManagementDOS = dataParamManagementDAO
                .selectList(Wrappers.<ConfigDataParamManagementDO>lambdaQuery()
                        .ne(ConfigDataParamManagementDO::getStatus, 9)
                        .in(ConfigDataParamManagementDO::getId, dataParamIds));
        if (CollUtil.isEmpty(configDataParamManagementDOS)) {
            return Collections.emptyList();
        }
        List<ConfigDataParamManagementDTO> result = BeanUtils.copyToList(configDataParamManagementDOS, ConfigDataParamManagementDTO.class);
        // 获取参量对应的算法
        Map<Long, ConfigAlgorithDTO> mapAlgorithm = mapAlgorithm(dataParamIds);
        // 获取参量对应的标签
//        Map<Long, List<ConfigLabelDTO>> mapLabelList = mapConfigLabelList(dataParamIds);
        // 获取参量对应的参数
        Map<Long, List<ConfigParamDTO>> mapParam = mapConfigParamList(result);
        // 获取参量对应的警告
        Map<Long, List<ConfigAlarmDTO>> mapAlarmList = mapDataLabelList(dataParamIds);

        result.forEach(item -> {
            Long id = item.getId();
            Integer source = item.getSource();
            ConfigAlgorithDTO algorithm = mapAlgorithm.getOrDefault(id, new ConfigAlgorithDTO());
            if (DataParamSourceEnum.SYSTEM_CALCULATE.getCode().equals(source)) {
                item.setAlgorithmId(algorithm.getAlgorithId());
            }
            item.setConfigAlgorithDTO(algorithm);
//            item.setConfigLabelDTOList(mapLabelList.getOrDefault(id, new ArrayList<>()));
            item.setConfigParamDTOList(mapParam.getOrDefault(id, new ArrayList<>()));
            item.setConfigAlarmDTOList(mapAlarmList.getOrDefault(id, new ArrayList<>()));
        });
        return result;
    }

    /**
     * 按 ID 列出
     *
     * @param dataParamIds 数据参数 ID
     * @return {@link List}<{@link ConfigDataParamManagementDTO}>
     */
    @Override
    public Map<Long, ConfigDataParamManagementDTO> mapByIds(List<Long> dataParamIds) {
        List<ConfigDataParamManagementDTO> result = listByIds(dataParamIds);
        return result.stream().collect(Collectors.toMap(ConfigDataParamManagementDTO::getId, item -> item));
    }

    /**
     * 通过codes获取
     * @param codes 参量code
     * @return
     */
    @Override
    public List<ConfigDataParamManagementDTO> listByCodes(List<String> codes) {
        List<ConfigDataParamManagementDO> managementDOS = dataParamManagementDAO.selectList(Wrappers
                        .<ConfigDataParamManagementDO>lambdaQuery()
                .in(ConfigDataParamManagementDO::getCode, codes)
                .eq(ConfigDataParamManagementDO::getStatus, 0));
        return BeanUtils.copyToList(managementDOS, ConfigDataParamManagementDTO.class);
    }

    @Override
    public List<ConfigDataParamManagementDTO> listByParams(DataParamQueryDTO dataParamQueryDTO) {
        ConfigDataParamManagementPageDTO management = BeanUtils.copyToObject(dataParamQueryDTO, ConfigDataParamManagementPageDTO.class);
        LambdaQueryWrapper<ConfigDataParamManagementDO> queryWrapper = buildQueryWrapper(management, new ArrayList<>());
        List<ConfigDataParamManagementDO> managements = dataParamManagementDAO.selectList(queryWrapper);
        return BeanUtils.copyToList(managements, ConfigDataParamManagementDTO.class);
    }


    /**
     *
     * @param devicePageQueryVO
     * @return
     */
    @Override
    public List<Long> queryParamsByParam(DevicePageQueryVO devicePageQueryVO) {
        List<Long> paramIds = dataParamManagementDAO.selectDeviceParams(devicePageQueryVO);
        List<Long> sortParamIds = paramIds.stream().distinct().collect(Collectors.toList());
        return sortParamIds;
    }

    @Override
    public List<DeviceParamDTO> queryDataByParamIds(List<Long> paramIds) {
        if (CollectionUtil.isEmpty(paramIds)){
            return new ArrayList<>();
        }
        List<DevicePageQueryDO> deviceParamDOs = dataParamManagementDAO.queryDataByParamIds(paramIds);
        List<DeviceParamDTO> deviceParams = BeanUtils.copyToList(deviceParamDOs, DeviceParamDTO.class);
        return deviceParams;
    }

        /**
     * 根据参数ID和名称查询数据
     *
     * @param DataParamIds 数据参数ID列表
     * @param factorName 数据参数名称
     * @return 符合条件的数据参数DTO列表
     */
    @Override
    public List<ConfigDataParamManagementDTO> queryDataByParamIdsAndName(List<Long> DataParamIds, String factorName) {
        LambdaQueryWrapper<ConfigDataParamManagementDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ConfigDataParamManagementDO::getStatus, 0);
        if (StringUtils.isNotEmpty(factorName)) {
            wrapper.like(ConfigDataParamManagementDO::getName, factorName);
        }
        if (CollectionUtil.isNotEmpty(DataParamIds)) {
            wrapper.in(ConfigDataParamManagementDO::getId, DataParamIds);
        }
        return BeanUtils.copyToList(dataParamManagementDAO.selectList(wrapper), ConfigDataParamManagementDTO.class);
    }

    /**
     * 查询设备和数据参量
     * @param pageDeviceDataParamQuery
     * @return
     */
    @Override
    public List<DeviceDataParamQueryDTO> getDeaviceAndDataParams(PageDeviceDataParamQueryDTO pageDeviceDataParamQuery) {
        List<DeviceDataParamQueryDTO> deaviceAndDataParams = dataParamManagementDAO.getDeviceAndDataParams(pageDeviceDataParamQuery);
        return deaviceAndDataParams;
    }

    @Override
    public void updateDataParamName(String equipmentName, List<Long> dataParamIdList) {
//        LambdaUpdateWrapper<ConfigDataParamManagementDO> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.setSql("name = CONCAT('${name}', '-', unified_identifier_name)");
//        updateWrapper.in(ConfigDataParamManagementDO::getId, dataParamIdList);
//        dataParamManagementDAO.update(null, updateWrapper);
        ItemBO itemBO = new ItemBO();
        itemBO.setName(equipmentName);
        itemBO.setList(dataParamIdList);
        dataParamManagementDAO.updateDataParamName(itemBO);
//
//        dataParamIdList.forEach(id -> {
//            ConfigDataParamManagementDO configDataParamManagementDO = dataParamManagementDAO.selectById(id);
//            if (configDataParamManagementDO!= null) {
//                configDataParamManagementDO.setName(equipmentName + "-" + configDataParamManagementDO.getUnifiedIdentifierName());
//                dataParamManagementDAO.updateById(configDataParamManagementDO);
//            }
//        });
    }

    /**
     * 通过code查参量名
     * @param code
     * @return
     */
    @Override
    public ConfigDataParamManagementDTO getParamNameByCode(String code) {
        ConfigDataParamManagementDO configDataParamManagementDO = dataParamManagementDAO.selectOne(Wrappers.lambdaQuery(ConfigDataParamManagementDO.class)
                .eq(ConfigDataParamManagementDO::getCode, code).ne(ConfigDataParamManagementDO::getStatus, GenericStatusEnum.DELETED.getValue()));
        return BeanUtils.copyToObject(configDataParamManagementDO,ConfigDataParamManagementDTO.class);
    }

    private List<ConfigDataParamManagementDTO> listByWrappers(LambdaQueryWrapper<ConfigDataParamManagementDO> wrapper) {
        List<ConfigDataParamManagementDO> configDataParamManagementList = dataParamManagementDAO
                .selectList(wrapper);

        if (CollUtil.isEmpty(configDataParamManagementList)) {
            return CollUtil.newArrayList();
        }

        List<Long> dataParamIds = configDataParamManagementList.stream()
                .map(ConfigDataParamManagementDO::getId)
                .distinct()
                .collect(Collectors.toList());

        return listByIds(dataParamIds);
    }

    /**
     * 通过参量id删除关联的公式以及参数。
     *
     * @param id
     */
    private void deleteAlgorithmByParamId(Long id) {

        QueryWrapper<ConfigDataParamAlgorithmRelationDO> algmRelationWrapper = new QueryWrapper<>();
        algmRelationWrapper.eq("data_param_id", id);
        List<ConfigDataParamAlgorithmRelationDO> algRelationList = algorithmRelationDAO.selectList(algmRelationWrapper);
        if (CollectionUtil.isEmpty(algRelationList)) {
            return;
        }
        List<Long> algIdList = algRelationList.stream().map(ConfigDataParamAlgorithmRelationDO::getAlgorithmId).collect(Collectors.toList());
        algorithmRelationDAO.delete(algmRelationWrapper);
        // 获取算法
        DataAlgorithmDO dataAlgorithmDO = dataAlgorithmDAO.selectById(algIdList.get(0));
        // 获取公式对应的参数
        List<Long> algParamIdList;
        if ("计算公式配置".equals(dataAlgorithmDO.getConfigurationScheme())) {
            // 获取公式数据
            QueryWrapper<DataAlgorithmFormulaConfigDO> formulaWrapper = new QueryWrapper<>();
            formulaWrapper.eq("algorithm_id", dataAlgorithmDO.getId());
            List<DataAlgorithmFormulaConfigDO> dataAlgorithmFormulaConfigDOS = dataAlgorithmFormulaConfigDAO.selectList(formulaWrapper);
            if (CollectionUtil.isEmpty(dataAlgorithmFormulaConfigDOS)) {
                return;
            }
            DataAlgorithmFormulaConfigDO dataAlgorithmFormulaConfigDO = dataAlgorithmFormulaConfigDOS.get(0);
            algParamIdList = dataAlgorithmFormulaConfigDOS.stream().map(DataAlgorithmFormulaConfigDO::getAlgorithmParamId).collect(Collectors.toList());
        } else {
            // 获取公式数据
            QueryWrapper<DataAlgorithmScriptConfigDO> scriptWrapper = new QueryWrapper<>();
            scriptWrapper.eq("algorithm_id", dataAlgorithmDO.getId());
            List<DataAlgorithmScriptConfigDO> algorithmScriptList = scriptConfigDAO.selectList(scriptWrapper);
            if (CollectionUtil.isEmpty(algorithmScriptList)) {
                return;
            }
            DataAlgorithmScriptConfigDO scriptConfigDO = algorithmScriptList.get(0);
            algParamIdList = algorithmScriptList.stream().map(DataAlgorithmScriptConfigDO::getParamConfigurationId).collect(Collectors.toList());
        }
        // 参数这些参数和参量关联信息
        QueryWrapper<ConfigDataParamAlgorithmParamRelationDO> paramRelationWrapper = new QueryWrapper<>();
        paramRelationWrapper.in("algorith_param_id", algParamIdList);
        paramRelationWrapper.eq("parent_param_id", id);
        paramRelationDAO.delete(paramRelationWrapper);
    }

    /**
     * 通过参数删除警告。
     *
     * @param id
     */
    private void deleteAlarmByParamId(Long id) {
        // 删除警告部分
        QueryWrapper<ConfigDataParamAlarmRelationDO> alarmRelationDOQueryWrapper = new QueryWrapper<>();
        alarmRelationDOQueryWrapper.eq("data_param_id", id);
        List<ConfigDataParamAlarmRelationDO> alarmRelationDOList = configDataParamAlarmRelationDAO.selectList(alarmRelationDOQueryWrapper);
        if (CollectionUtil.isEmpty(alarmRelationDOList)) {
            return;
        }
        List<Long> alaramIdList = alarmRelationDOList.stream().map(ConfigDataParamAlarmRelationDO::getAlarmId).collect(Collectors.toList());
        // 删除警告
        dataAlarmDAO.deleteBatchIds(alaramIdList);
        configDataParamAlarmRelationDAO.delete(alarmRelationDOQueryWrapper);
    }

    /**
     * 配置标签数据
     *
     * @param data
     */
//    private void setLabelDataList(Collection<ConfigDataParamManagementDTO> data) {
//        data.forEach(relationDTO -> {
//            QueryWrapper<ConfigDataParamLabelRelationDO> wrapper = new QueryWrapper<>();
//            wrapper.eq("data_param_id", relationDTO.getId());
//            List<ConfigDataParamLabelRelationDO> relationDOList = dataParamLabelRelationDAO.selectList(wrapper);
//            List<Long> labelItemIdList = relationDOList.stream().map(ConfigDataParamLabelRelationDO::getLableItemId).collect(Collectors.toList());
//            if (CollectionUtil.isEmpty(labelItemIdList)) {
//                return;
//            }
//            // 查询依赖
//            QueryWrapper<DataLabelItemRelationDO> itemRelationDOQueryWrapper = new QueryWrapper<>();
//            itemRelationDOQueryWrapper.in("label_item_id", labelItemIdList);
//            List<DataLabelItemRelationDO> itemRelationDOList = dataLabelItemRelationDAO.selectList(itemRelationDOQueryWrapper);
//            if (CollectionUtil.isEmpty(itemRelationDOList)) {
//                return;
//            }
//            List<Long> labelIdList = itemRelationDOList.stream().map(DataLabelItemRelationDO::getLabelId).collect(Collectors.toList());
//            // 查询标签项
//            QueryWrapper<DataLabelItemDO> itemDOQueryWrapper = new QueryWrapper<>();
//            itemDOQueryWrapper.in("id", labelItemIdList);
//            List<DataLabelItemDO> dataLabelItemDOS = dataLabelItemDAO.selectList(itemDOQueryWrapper);
//            Map<Long, List<DataLabelItemDO>> labelItemDOMap = dataLabelItemDOS.stream().collect(Collectors.groupingBy(DataLabelItemDO::getId));
//            // 查询标签
//            QueryWrapper<DataLabelDO> labelDOQueryWrapper = new QueryWrapper<>();
//            labelDOQueryWrapper.in("id", labelIdList);
//            List<DataLabelDO> dataLabelDOS = dataLabelDAO.selectList(labelDOQueryWrapper);
//            Map<Long, List<DataLabelDO>> dataLabelDOMap = dataLabelDOS.stream().collect(Collectors.groupingBy(DataLabelDO::getId));
//            List<ConfigLabelDTO> configLabelDTOList = new ArrayList<>();
//            relationDTO.setConfigLabelDTOList(configLabelDTOList);
//            itemRelationDOList.forEach(itemRelationDO -> {
//                List<DataLabelItemDO> secondDataLabelItemDOS = labelItemDOMap.get(itemRelationDO.getLabelItemId());
//                List<DataLabelDO> secondDataLabelDOS = dataLabelDOMap.get(itemRelationDO.getLabelId());
//                ConfigLabelDTO configLabelDTO = new ConfigLabelDTO();
//                configLabelDTO.setLabelName(secondDataLabelDOS.get(0).getLabelName());
//                configLabelDTO.setLabelItemName(secondDataLabelItemDOS.get(0).getLabelItemName());
//                configLabelDTO.setLabelItemPath(secondDataLabelItemDOS.get(0).getItemPath());
//                configLabelDTO.setLabelItemId(secondDataLabelItemDOS.get(0).getId());
//                configLabelDTOList.add(configLabelDTO);
//            });
//        });
//    }

    /**
     * 获取分页数据。
     *
     * @param paramManagementPageDTO
     * @return
     */
    private PageData<ConfigDataParamManagementDO> dataParamManagement(ConfigDataParamManagementPageDTO paramManagementPageDTO) {
        // 封装查询条件QueryWrapper对象

        LambdaQueryWrapper<ConfigDataParamManagementDO> queryWrapper = buildQueryWrapper(paramManagementPageDTO, paramManagementPageDTO.getIdList());
//        if (CollUtil.isNotEmpty(paramManagementPageDTO.getIdList())){
//            queryWrapper.in("id",paramManagementPageDTO.getIdList());
//        }
//        queryWrapper.orderByDesc("id");
        // 分页查询数据报警点管理信息
        Page<ConfigDataParamManagementDO> page = Page.of(paramManagementPageDTO.getPageNo(), paramManagementPageDTO.getPageSize());
        PageData<ConfigDataParamManagementDO> pageDataForDO = PageUtils.getPageData(dataParamManagementDAO.selectPage(page, queryWrapper), paramManagementPageDTO);
        return pageDataForDO;
    }

    /**
     * 获取分页数据。
     *
     * @param paramManagementPageDTO
     * @param findManageIdList
     * @return
     */
    private PageData<ConfigDataParamManagementDO> pageManagement(ConfigDataParamManagementPageDTO paramManagementPageDTO, List<Long> findManageIdList) {
        Page<ConfigDataParamManagementDO> page = Page.of(paramManagementPageDTO.getPageNo(), paramManagementPageDTO.getPageSize());
        Page<ConfigDataParamManagementDO> managementPage = dataParamManagementDAO.selectPage(page, buildQueryWrapper(paramManagementPageDTO, findManageIdList));
        return PageUtils.getPageData(managementPage, paramManagementPageDTO);
    }

    private LambdaQueryWrapper<ConfigDataParamManagementDO> buildQueryWrapper(ConfigDataParamManagementPageDTO paramManagementPageDTO,
                                                                              List<Long> findManageIdList) {
        LambdaQueryWrapper<ConfigDataParamManagementDO> managementDOQueryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(paramManagementPageDTO.getIdList())
                .ifPresent(ids -> managementDOQueryWrapper.in(ConfigDataParamManagementDO::getId, ids));
        Optional.ofNullable(paramManagementPageDTO.getIdNotList())
                .ifPresent(ids -> managementDOQueryWrapper.notIn(ConfigDataParamManagementDO::getId, ids));
        Optional.ofNullable(paramManagementPageDTO.getCode())
                .ifPresent(code -> managementDOQueryWrapper.eq(ConfigDataParamManagementDO::getCode, code));
        Optional.ofNullable(paramManagementPageDTO.getName())
                .ifPresent(name -> managementDOQueryWrapper.like(ConfigDataParamManagementDO::getName, name));
        Optional.ofNullable(paramManagementPageDTO.getSource())
                .ifPresent(source -> managementDOQueryWrapper.eq(ConfigDataParamManagementDO::getSource, source));
        Optional.ofNullable(paramManagementPageDTO.getAlias())
                .ifPresent(alias -> managementDOQueryWrapper.eq(ConfigDataParamManagementDO::getAlias, alias));
        Optional.ofNullable(paramManagementPageDTO.getReportIdentifier())
                .ifPresent(reportIdentifier -> managementDOQueryWrapper
                        .eq(ConfigDataParamManagementDO::getReportIdentifier, reportIdentifier));
        Optional.ofNullable(paramManagementPageDTO.getUnifiedIdentifier())
                .ifPresent(unifiedIdentifier -> managementDOQueryWrapper
                        .eq(ConfigDataParamManagementDO::getUnifiedIdentifier, unifiedIdentifier));
        Optional.ofNullable(paramManagementPageDTO.getFrequencyUnit())
                .ifPresent(unit -> managementDOQueryWrapper
                        .eq(ConfigDataParamManagementDO::getFrequencyUnit, unit));
        Optional.ofNullable(paramManagementPageDTO.getFrequency())
                .ifPresent(frequency -> managementDOQueryWrapper
                        .eq(ConfigDataParamManagementDO::getFrequency, frequency));
        Optional.ofNullable(paramManagementPageDTO.getMeasurementUnit())
                .ifPresent(unit -> managementDOQueryWrapper
                        .eq(ConfigDataParamManagementDO::getMeasurementUnit, unit));
        Optional.ofNullable(paramManagementPageDTO.getDataType())
                .ifPresent(type -> managementDOQueryWrapper
                        .eq(ConfigDataParamManagementDO::getDataType, type));
        Optional.ofNullable(paramManagementPageDTO.getCreateTimeList())
                .ifPresent(time -> managementDOQueryWrapper
                        .between(ConfigDataParamManagementDO::getCreateTime, time.get(0), time.get(1)));
        Optional.ofNullable(paramManagementPageDTO.getCreatorName())
                .ifPresent(name -> managementDOQueryWrapper
                        .eq(ConfigDataParamManagementDO::getCreatorName, name));
        if (CollUtil.isNotEmpty(paramManagementPageDTO.getUnifiedIdentifiers())){
            managementDOQueryWrapper.in(ConfigDataParamManagementDO::getUnifiedIdentifier, paramManagementPageDTO.getUnifiedIdentifiers());
        }
        if (CollUtil.isNotEmpty(findManageIdList)) {
            managementDOQueryWrapper.in(ConfigDataParamManagementDO::getId, findManageIdList);
        }
        List<Integer> statusList = paramManagementPageDTO.getStatusList();
        if (CollUtil.isNotEmpty(statusList)) {
            managementDOQueryWrapper.in(ConfigDataParamManagementDO::getStatus, statusList);
        } else {
            managementDOQueryWrapper.eq(ConfigDataParamManagementDO::getStatus, 0);
        }
        managementDOQueryWrapper.orderByDesc(ConfigDataParamManagementDO::getId);  // 通过id倒序。
        return managementDOQueryWrapper;
    }

//    /**
//     * 更新算法和参数依赖。
//     *
//     * @param configDataParamManagementDTO
//     * @param manageId
//     */
//    private void saveOrUpdateAlgorithm(ConfigDataParamManagementDTO configDataParamManagementDTO, Long manageId) {
//        // 删除上次的关联关系
//        algorithmRelationDAO.delete(Wrappers.<ConfigDataParamAlgorithmRelationDO>lambdaQuery()
//                .eq(ConfigDataParamAlgorithmRelationDO::getDataParamId, manageId));
//        // 插入数据变量算法依赖
//        if (configDataParamManagementDTO.getAlgorithmId() != null) {
//            ConfigDataParamAlgorithmRelationDO configDataParamAlgorithmRelationDO = new ConfigDataParamAlgorithmRelationDO();
//            configDataParamAlgorithmRelationDO.setDataParamId(manageId);
//            configDataParamAlgorithmRelationDO.setAlgorithmId(configDataParamManagementDTO.getAlgorithmId());
//            setCreateDefaultField(configDataParamAlgorithmRelationDO, configDataParamManagementDTO);
//            algorithmRelationDAO.insert(configDataParamAlgorithmRelationDO);
//        }
//        // 更新参数参量对应数据
//        saveOrUpdateParamList(configDataParamManagementDTO);
//    }

//    /**
//     * 更新参数参量对应数据。
//     *
//     * @param configDataParamManagementDTO
//     */
//    private void saveOrUpdateParamList(ConfigDataParamManagementDTO configDataParamManagementDTO) {
//        Long id = configDataParamManagementDTO.getId();
//        Assert.notNull(id, "参量id不能为空");
//
//        paramRelationDAO.delete(Wrappers.<ConfigDataParamAlgorithmParamRelationDO>lambdaQuery()
//                .eq(ConfigDataParamAlgorithmParamRelationDO::getParentParamId, id));
////        deleteLastParamRelation(configDataParamAlgorithmRelationDO, configDataParamManagementDTO.getId());
//        // 判定当前有没有需要插入的参数数据，如果没有则返回。
//        List<ConfigParamDTO> configParamDTOList = configDataParamManagementDTO.getConfigParamDTOList();
//        if (CollectionUtil.isEmpty(configParamDTOList)) {
//            return;
//        }
//        List<ConfigDataParamAlgorithmParamRelationDO> dataAlgorithParamRelationDOList = new ArrayList<>();
//        configParamDTOList.forEach(configParamDTO -> {
//            // 剔除 全局变量
//            if ("全局变量".equals(configParamDTO.getParamType())) {
//                return;
//            }
//            ConfigDataParamAlgorithmParamRelationDO configDataParamAlgorithmParamRelationDO = new ConfigDataParamAlgorithmParamRelationDO();
//            configDataParamAlgorithmParamRelationDO.setAlgorithParamId(configParamDTO.getParamId());
//            configDataParamAlgorithmParamRelationDO.setDataParamId(configParamDTO.getVariableId());
//            configDataParamAlgorithmParamRelationDO.setParentParamId(id);
//            setCreateDefaultField(configDataParamAlgorithmParamRelationDO, configDataParamManagementDTO);
//            dataAlgorithParamRelationDOList.add(configDataParamAlgorithmParamRelationDO);
//        });
//        if (CollectionUtil.isEmpty(dataAlgorithParamRelationDOList)) {
//            return;
//        }
//        paramRelationDAO.insertBatch(dataAlgorithParamRelationDOList);
//    }

//    /**
//     * 更新标签数据
//     *
//     * @param configDataParamManagementDTO
//     * @param dataParamId
//     */
//    private void saveOrUpdateLabelList(ConfigDataParamManagementDTO configDataParamManagementDTO, Long dataParamId) {
//        // 删除上次的关联关系
//        dataParamLabelRelationDAO.delete(Wrappers.<ConfigDataParamLabelRelationDO>lambdaQuery()
//                .eq(ConfigDataParamLabelRelationDO::getDataParamId, dataParamId));
//        // 插入数据标签依赖
//        List<ConfigLabelDTO> configLabelDTOList = configDataParamManagementDTO.getConfigLabelDTOList();
//        // 防止空指针
//        configLabelDTOList = CollectionUtil.isEmpty(configLabelDTOList) ? new ArrayList<>() : configLabelDTOList;
//
//        List<ConfigDataParamLabelRelationDO> labelRelationList = new ArrayList<>();
//        configLabelDTOList.forEach(configLabelDTO -> {
//            ConfigDataParamLabelRelationDO configDataParamLabelRelationDO = new ConfigDataParamLabelRelationDO();
//            configDataParamLabelRelationDO.setLableItemId(configLabelDTO.getLabelItemId());
//            configDataParamLabelRelationDO.setDataParamId(dataParamId);
//            setCreateDefaultField(configDataParamLabelRelationDO, configDataParamManagementDTO);
//            labelRelationList.add(configDataParamLabelRelationDO);
//        });
//        // add 默认统一标识标签
//        addUnifiedIdentifierLabel(labelRelationList, configDataParamManagementDTO.getUnifiedIdentifierName(), dataParamId);
//        if (CollectionUtil.isEmpty(labelRelationList)) {
//            return;
//        }
//        dataParamLabelRelationDAO.insertBatch(labelRelationList);
//    }

//    /**
//     * 设置默认统一标识标签
//     *
//     * @param labelRelationList     标签关系列表
//     * @param unifiedIdentifierName 统一标识符名称
//     * @param dataParamId          参量ID
//     */
//    private void addUnifiedIdentifierLabel(List<ConfigDataParamLabelRelationDO> labelRelationList,
//                                           String unifiedIdentifierName, Long dataParamId) {
//        DataLabelItemDO dataLabelItemDO = dataLabelItemDAO.selectOne(Wrappers.<DataLabelItemDO>lambdaQuery()
//                .eq(DataLabelItemDO::getLabelItemName, unifiedIdentifierName)
//                .last("limit 1"));
//        if (ObjectUtil.isNotNull(dataLabelItemDO)) {
//            Long id = dataLabelItemDO.getId();
//            List<ConfigDataParamLabelRelationDO> temp = labelRelationList.stream()
//                    .filter(item -> item.getLableItemId().equals(id))
//                    .collect(Collectors.toList());
//            if (CollectionUtil.isNotEmpty(temp)) {
//                return;
//            }
//            ConfigDataParamLabelRelationDO labelRelation = new ConfigDataParamLabelRelationDO();
//            labelRelation.setLableItemId(dataLabelItemDO.getId());
//            labelRelation.setDataParamId(dataParamId);
//            labelRelationList.add(labelRelation);
//        }
//    }

    /**
     * 设置创建默认字段
     *
     * @param t                            t
     * @param configDataParamManagementDTO 配置数据参数管理 DTO
     * @return {@link T}
     */
    public static <T extends BaseDO> T setCreateDefaultField(T t, ConfigDataParamManagementDTO configDataParamManagementDTO) {
        t.setCreatorId(configDataParamManagementDTO.getCreatorId());
        t.setCreatorName(configDataParamManagementDTO.getCreatorName());
        t.setCreateTime(configDataParamManagementDTO.getCreateTime());
        t.setLastUpdaterId(configDataParamManagementDTO.getLastUpdaterId());
        t.setLastUpdaterName(configDataParamManagementDTO.getLastUpdaterName());
        t.setLastUpdateTime(configDataParamManagementDTO.getLastUpdateTime());
        return t;
    }



    //设备模型参量
    public  static  final  String EXCEL_DATA_PARAM_VO = "ExcelDataParamVO";
    //参量频率
    public  static  final String EXCEL_FREQUENCY_VO = "ExcelFrequencyVO";
    //算法
    public  static  final String ALGORITHM_EXCEL_VO = "AlgorithmExcelVO";
    //算法参数
    public  static  final String EXCEL_ALGORITHM_PARAM_VO = "ExcelAlgorithmParamVO";
    //参量标签
    public  static  final String EXCEL_LABEL_VO = "ExcelLabelVO";
    //设备告警
    public  static  final String EXCEL_ALARM_VO = "ExcelAlarmVO";




    /**
     * 更新状态
     *
     * @param status          地位
     * @param dataParamIdList 数据参数 ID 列表
     */
    @Override
    public void updateStatus(Integer status, List<Long> dataParamIdList) {
        LambdaUpdateWrapper<ConfigDataParamManagementDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ConfigDataParamManagementDO::getStatus, status).in(ConfigDataParamManagementDO::getId, dataParamIdList);
        dataParamManagementDAO.update(null, updateWrapper);
    }

    /**
     * 校验重复
     * @param configDataParamManagementDOS
     */
    public void checkDup(List<ConfigDataParamManagementDO> configDataParamManagementDOS) {
        Map<String, List<ConfigDataParamManagementDO>> configDataGroup = configDataParamManagementDOS.stream().collect(Collectors.groupingBy(ConfigDataParamManagementDO::getName));
        StringBuilder error = new StringBuilder();
        configDataGroup.forEach((k,v)->{
            if(CollectionUtils.isNotEmpty(v) && v.size() > 1){
                error.append(k + ";");
            }
        });

        //库中是否存在
        List<String> manNames = configDataParamManagementDOS.stream().map(ConfigDataParamManagementDO::getName).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(manNames)){
            return;
        }

        QueryWrapper<ConfigDataParamManagementDO> configWrapper = new QueryWrapper<>();
        configWrapper.lambda().eq(ConfigDataParamManagementDO::getStatus,0)
                .in(CollectionUtils.isNotEmpty(manNames), ConfigDataParamManagementDO::getName,manNames);
        List<ConfigDataParamManagementDO> list = this.list(configWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(e-> error.append(e.getName() + ";"));
        }
        if(StringUtils.isNotEmpty(error.toString())){
            throw new ServiceException("参量名称重复：" + error.toString());
        }
    }





    /**
     * 设置算法和参量的绑定
     * @param excelAlgorithmParamDTOs
     * @param dataParamMapByName
     * @param algorithmMapByName
     */
    public void initParamRealtion(List<ExcelAlgorithmParamDTO> excelAlgorithmParamDTOs, Map<String, Long> dataParamMapByName, Map<String, Long> algorithmMapByName) {
        if(CollectionUtils.isEmpty(excelAlgorithmParamDTOs) || CollectionUtils.isEmpty(algorithmMapByName)){
            return;
        }

        //算法的形参和实参绑定
        //所有算法参量涉及的算法id
        Set<Long> algorithmIdByParam =
                excelAlgorithmParamDTOs.stream().map(e -> algorithmMapByName.get(e.getAlgorithmName())).collect(Collectors.toSet());
        QueryWrapper<DataAlgorithmFormulaConfigDO> dataAlgorithmFormulaConfigDOQueryWrapper = new QueryWrapper<>();
        dataAlgorithmFormulaConfigDOQueryWrapper.lambda()
                .in(CollectionUtils.isNotEmpty(algorithmIdByParam), DataAlgorithmFormulaConfigDO::getAlgorithmId,algorithmIdByParam);
        List<DataAlgorithmFormulaConfigDO> algorithmConfigS =
                dataAlgorithmFormulaConfigDAO.selectList(dataAlgorithmFormulaConfigDOQueryWrapper);
        if(CollectionUtils.isEmpty(algorithmConfigS)){
            return;
        }
        //算法对应的参量信息
        Set<Long> algorithmParamIds =
                algorithmConfigS.stream().map(DataAlgorithmFormulaConfigDO::getAlgorithmParamId).collect(Collectors.toSet());
        QueryWrapper<DataAlgorithmParamConfigDO> dataAlgorithmParamConfigWrapper = new QueryWrapper<>();
        dataAlgorithmParamConfigWrapper.lambda()
                .in(CollectionUtils.isNotEmpty(algorithmParamIds), DataAlgorithmParamConfigDO::getId,algorithmParamIds);
        List<DataAlgorithmParamConfigDO> dataAlgorithmParamConfigDOS =
                dataAlgorithmParamConfigDAO.selectList(dataAlgorithmParamConfigWrapper);
        if(CollectionUtils.isEmpty(dataAlgorithmParamConfigDOS)){
            return;
        }
        Map<Long, String> dataAlgorithmParamConfigById =
                dataAlgorithmParamConfigDOS.stream().collect(Collectors.toMap(DataAlgorithmParamConfigDO::getId, DataAlgorithmParamConfigDO::getDescription));
        //设置参量描述
        algorithmConfigS.forEach(e->e.setAlgorithmParamName(dataAlgorithmParamConfigById.get(e.getAlgorithmParamId())));

        //按算法和算法参量名称分组
        Map<String, Long> collect =
                algorithmConfigS.stream().collect(Collectors.toMap(e -> e.getAlgorithmId() + "/" + e.getAlgorithmParamName(), e -> e.getAlgorithmParamId()));

        List<ConfigDataParamAlgorithmParamRelationDO> configDataParamAlgorithmParamRelationDOS = new ArrayList<>();
        for (ExcelAlgorithmParamDTO excelAlgorithmParamDTO : excelAlgorithmParamDTOs) {
            if("全局变量".equals(excelAlgorithmParamDTO.getParamType())){
                continue;
            }
            Long parentParamId = dataParamMapByName.get(excelAlgorithmParamDTO.getDataParamName());
            Long algoritId = algorithmMapByName.get(excelAlgorithmParamDTO.getAlgorithmName());
            Long paramId = dataParamMapByName.get(excelAlgorithmParamDTO.getBindDataParamName());
            Long algoritParamId = collect.get(algoritId + "/" + excelAlgorithmParamDTO.getParamDesc());
            if(Objects.nonNull(parentParamId) && Objects.nonNull(algoritId) && Objects.nonNull(paramId) && Objects.nonNull(algoritParamId)){
                ConfigDataParamAlgorithmParamRelationDO configDataParamAlgorithmParamRelationDO = new ConfigDataParamAlgorithmParamRelationDO();
                configDataParamAlgorithmParamRelationDO.setParentParamId(parentParamId);
                configDataParamAlgorithmParamRelationDO.setDataParamId(paramId);
                configDataParamAlgorithmParamRelationDO.setAlgorithParamId(algoritParamId);
                configDataParamAlgorithmParamRelationDOS.add(configDataParamAlgorithmParamRelationDO);

            }

        }
        if(CollectionUtils.isNotEmpty(configDataParamAlgorithmParamRelationDOS)){
            paramRelationDAO.insertBatch(configDataParamAlgorithmParamRelationDOS);

        }
    }

    //设置标签和算法的关系
//    public void initLabel(List<ExcelLabelDTO> excelLabelDTOs, Map<String, Long> dataParamMapByName) {
//        if(CollectionUtils.isEmpty(excelLabelDTOs)){
//            return;
//        }
//
//
//        Set<String> excelLabelPaths = excelLabelDTOs.stream().map(ExcelLabelDTO::getLabelItemPath).collect(Collectors.toSet());
//        //DataLabelItemDO
//        QueryWrapper<DataLabelItemDO> dataLabelItemDOQueryWrapper = new QueryWrapper<>();
//        dataLabelItemDOQueryWrapper.lambda()
//                .in(CollectionUtils.isNotEmpty(excelLabelPaths), DataLabelItemDO::getItemPath,excelLabelPaths);
//        List<DataLabelItemDO> dataLabelItemDOS = dataLabelItemDAO.selectList(dataLabelItemDOQueryWrapper);
//        if(CollectionUtils.isEmpty(dataLabelItemDOS)){
//            return;
//        }
//        Map<String, Long> dataLabelItemByName = dataLabelItemDOS.stream().collect(Collectors.toMap(DataLabelItemDO::getItemPath, DataLabelItemDO::getId));
//
//        List<ConfigDataParamLabelRelationDO> configDataParamLabelRelationDOS = new ArrayList<>();
//        excelLabelDTOs.forEach(e->{
//            Long dataLabelItemId = dataLabelItemByName.get(e.getLabelItemPath());
//            Long dataParamId = dataParamMapByName.get(e.getDataParamName());
//            if(Objects.nonNull(dataLabelItemId) && Objects.nonNull(dataParamId)){
//                ConfigDataParamLabelRelationDO configDataParamLabelRelationDO = new ConfigDataParamLabelRelationDO();
//                configDataParamLabelRelationDO.setLableItemId(dataLabelItemId);
//                configDataParamLabelRelationDO.setDataParamId(dataParamId);
//                configDataParamLabelRelationDOS.add(configDataParamLabelRelationDO);
//
//            }
//
//        });
//        dataParamLabelRelationDAO.insertBatch(configDataParamLabelRelationDOS);
//    }

    /**
     * 设置警告和算法
     * @param excelAlarmDTOs
     * @param listParam
     */
    public void initAlarm(List<ExcelAlarmDTO> excelAlarmDTOs, List<ConfigDataParamManagementDO> listParam) {
        if(CollectionUtils.isEmpty(excelAlarmDTOs)){
            return;
        }
        Map<String, ConfigDataParamManagementDO> managementByName =
                listParam.stream().collect(Collectors.toMap(ConfigDataParamManagementDO::getName, e -> e));
        List<DataAlarmDO> dataAlarmDOS = new ArrayList<>();
        for (ExcelAlarmDTO excelAlarmDTO : excelAlarmDTOs) {
            ConfigDataParamManagementDO configDataParamManagementDO = managementByName.get(excelAlarmDTO.getDataParamName());
            if(Objects.nonNull(configDataParamManagementDO)){
                DataAlarmDO dataAlarmDO = BeanUtils.copyToObject(excelAlarmDTO, DataAlarmDO.class);
                dataAlarmDO.setCode(configDataParamManagementDO.getCode());
                dataAlarmDO.setDataParamId(configDataParamManagementDO.getId());
                dataAlarmDO.setName(configDataParamManagementDO.getName());
                dataAlarmDO.setParameterName(configDataParamManagementDO.getAlias());
                dataAlarmDO.setSource(configDataParamManagementDO.getSource());
                dataAlarmDOS.add(dataAlarmDO);
            }
        }
        dataAlarmDAO.insertBatch(dataAlarmDOS);
    }
}
